package com.training.hatton.dropboxclient.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.training.hatton.base.processor.BaseProcessor;
import com.training.hatton.dropboxclient.R;
import com.training.hatton.dropboxclient.content.Metadata;
import com.training.hatton.dropboxclient.service.ServiceHelper;
import com.training.hatton.dropboxclient.utill.DropboxService;
import com.training.hatton.dropboxclient.utill.ProcessorCallbackListener;

public class DropboxDetailsFragment extends Fragment implements  OnClickListener, ProcessorCallbackListener{

	private Metadata mData;
	
	@Override
	public void onResume() {
		ServiceHelper.get(getActivity()).registerProcessorCallbackListener(this);
		super.onResume();
	}
	@Override
	public void onPause() {
		ServiceHelper.get(getActivity()).removeProcessorCallbackListener(this);
		super.onPause();
	}
	

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_dropbox_details, null);
		Button btn_download = (Button) view.findViewById(R.id.btn_download);
		Button btn_delete = (Button) view.findViewById(R.id.btn_delete);
		btn_download.setOnClickListener(this);
		btn_delete.setOnClickListener(this);	
		mData = new Metadata(getArguments().getString(DropboxService.EXTRA_JSON));
		TextView nameTextView = (TextView) view.findViewById(R.id.tv_name_value);
		TextView bytesTextView = (TextView) view.findViewById(R.id.tv_bytes_value);
		nameTextView.setText(mData.getName());
		bytesTextView.setText(mData.getBytes());
		return view;
	}
	
	private void onDownload(View view){
		ServiceHelper.get(getActivity()).downloadFile(DropboxService.ROOT, mData.getPath(), mData.getRev());
	}
	
	private void onDelete(View view){
		ServiceHelper.get(getActivity()).deleteFile(DropboxService.ROOT, mData.getPath());
	}
	
	@Override
	public void onResult(int resultCode, Bundle resultData) {
		switch(resultCode){
		case BaseProcessor.SUCCESS_CODE:
			if(resultData.getString(DropboxService.EXTRA_ACTION).equals(DropboxService.ACTION_DELETE)){
				getFragmentManager().popBackStack();
			}
			break;
		case BaseProcessor.ERROR_CODE:
			Toast.makeText(getActivity(), ((Exception)resultData.getSerializable(DropboxService.EXTRA_ERROR)).getMessage(), Toast.LENGTH_LONG).show();
			break;
		}	
	}
	
	public void setData(Metadata md){
		mData = md;
	}
	public Metadata getData(){
		return mData;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_delete:
			onDelete(v);
			break;
		case R.id.btn_download:
			onDownload(v);
			break;
		}
	}
}